﻿using IDAdmin.Common;
using IDAdmin.Lib.DataLayer;
using IDAdmin.Lib.UI;
using IDAdmin.Lib.Utils;
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace IDAdmin.Pages
{
    public partial class GoldShopDataStatistics : BasePage
    {
        public GoldShopDataStatistics()
            : base(Lib.AppFunctions.GOLDSHOPDATASTATISTICS)
        {

        }
        protected override void Page_Load(object sender, EventArgs e)
        {
            if (!IsLogin())
            {
                RedirectToLogOn();
            }
            else if (!CheckRight())
            {
                RedirectToDeniedMessage();
            }
            if (!IsPostBack)
            {
                List<Server> listserver = WebDB_N.ListServer();
                ListItem l1 = new ListItem("--Tất cả--", "0");
                ServerListDropDownList1.Items.Add(l1);
                foreach (var item in listserver)
                {
                    ListItem l = new ListItem(item.zonename.ToString(), item.gamezone.ToString());
                    ServerListDropDownList1.Items.Add(l);
                }
            }  
        }

        protected void countButton_Click(object sender, EventArgs e)
        {
            DateTime dtFormDate = IDAdmin.Common.ConverterWorkData.convertStringToDateTime(countToolBar.beginDateTextBox.Text);
            DateTime dtToDate = IDAdmin.Common.ConverterWorkData.convertStringToDateTime(countToolBar.toDateTextBox.Text);
            List<DateTime> dateTimeList = IDAdmin.Common.ConverterWorkData.getDateListBetween(dtFormDate, dtToDate);
            dataPanel.Controls.Clear();
            System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
            watch.Start();
            List<OriginGoldShopData> ogsd = new List<OriginGoldShopData>();
            string itemname = "";
            itemname = itemnameTextBox1.Text;
            if (ServerListDropDownList1.SelectedValue != null)
            {
                ogsd = WebDB_N.getItemPurchasingData(dateTimeList, shopDropDownList.SelectedItem.Value, ServerListDropDownList1.SelectedValue, itemname); 
            }
            else
            {
                ogsd = WebDB_N.getItemPurchasingData(dateTimeList, shopDropDownList.SelectedItem.Value, "0", itemname); 
            }                        
            dataPanel.Controls.Add(count(ogsd));
            watch.Stop();
            double elapsedMS = watch.ElapsedMilliseconds;
            measureLB.Text = elapsedMS.ToString() + "miliseconds";
        }

        private Table count(List<OriginGoldShopData> itemPurchasingData)
        {
            Table table = new Table();
            table.CssClass = "table1";
            table.CellSpacing = 1;
            TableRow rowHeader = new TableRow();
            rowHeader.Cells.AddRange
            (
                new TableCell[]
                {     
                    UIHelpers.CreateTableCell("Ngày",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                     UIHelpers.CreateTableCell("Id vật phẩm",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                    UIHelpers.CreateTableCell("Tên vật phẩm",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                    UIHelpers.CreateTableCell("Tên cửa hàng",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                    UIHelpers.CreateTableCell("Đơn giá vật phẩm",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                    UIHelpers.CreateTableCell("Số lượng mua",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                    UIHelpers.CreateTableCell("Tổng vàng",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),                   
                    UIHelpers.CreateTableCell("Số lượng người đã mua",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader")                    
                }
            );

            table.Rows.Add(rowHeader);
            try
            {
                string css;
                int stt = 0;

                var queryDatapGoldshop = (from goldshop in itemPurchasingData
                                          group goldshop by new { goldshop.BaseId, goldshop.DateTime, goldshop.ItemName, goldshop.TmpInfo, goldshop.priceGold,goldshop.Action } into g
                                          select new
                                          {
                                              DateTime = g.Key.DateTime,
                                              BaseId = g.Key.BaseId,
                                              ItemName = g.Key.ItemName,
                                              TmpInfo = g.Key.TmpInfo,
                                              priceGold = g.Key.priceGold,
                                              action = g.Key.Action,
                                              TotalGoldSpend = g.Sum(z => Convert.ToInt32(z.TotalGoldSpend)).ToString(),
                                              MunUserby = g.Sum(z => Convert.ToInt32(z.MunUserby)).ToString()                                                                          
                                          }).ToList();

                foreach (var item in queryDatapGoldshop)
                {
                    stt++;
                    css = stt % 2 == 0 ? "cell1" : "cell2";
                    TableRow row = new TableRow();

                    row.Cells.AddRange
                    (
                        new TableCell[]
                                    {
                                        UIHelpers.CreateTableCell(item.DateTime.ToString(),HorizontalAlign.Center,css),
                                        UIHelpers.CreateTableCell( item.BaseId.ToString() ,HorizontalAlign.Center,css),
                                        UIHelpers.CreateTableCell(item.ItemName.ToString(),HorizontalAlign.Center,css),
                                         UIHelpers.CreateTableCell(item.TmpInfo == "-" ? item.action : item.TmpInfo.ToString(),HorizontalAlign.Center,css),
                                        UIHelpers.CreateTableCell(item.priceGold.ToString(),HorizontalAlign.Center,css), 
                                        UIHelpers.CreateTableCell(item.TotalGoldSpend.ToString(),HorizontalAlign.Center,css), 
                                        UIHelpers.CreateTableCell((Convert.ToInt32(item.priceGold) * Convert.ToInt32(item.TotalGoldSpend)).ToString("N0", CultureInfo.InvariantCulture),HorizontalAlign.Center,css), 
                                        UIHelpers.CreateTableCell(item.MunUserby.ToString(),HorizontalAlign.Center,css)
                                        
                                    }
                    );
                    table.Rows.Add(row);
                }
            }
            catch (Exception ex)
            {
            }
            return table;
        }

        /// <summary>
        /// function của Hòa
        /// </summary>
        /// <param name="itemPurchasingData"></param>
        /// <returns></returns>
        private Table _count(List<OriginGoldShopData> itemPurchasingData)
        {
            List<GoldShopData> gsdList = new List<GoldShopData>();
            //var itemNameList = (from tb in itemPurchasingData select tb.ItemName).Union(from tb in itemConsumingData select tb.ItemName).Distinct().ToList();
            var itemList = itemPurchasingData.GroupBy(g => new { g.ItemName, g.BaseId }).Select(s => new { s.Key.ItemName, s.Key.BaseId });
            // var itemPriceList = WebDB.getGoldPriceOfItem(itemList);

            var itemAndPurchasingNumList = (from tb in itemPurchasingData group tb by new { tb.BaseId, tb.ItemName } into grp select new { grp.Key.BaseId, grp.Key.ItemName, Sum = grp.Sum(s => int.Parse(s.PurchasingNum)) }).ToList();
            //var itemAndUsingNumList = (from tb in itemConsumingData group tb by new { tb.ItemName } into grp select new { grp.Key.ItemName, Sum = grp.Sum(s => int.Parse(s.PurchasingNum)) }).ToList();
            int purchasingNumColSum = 0;
            int GoldSumColSum = 0;
            int PurchasingPeopleNumColSum = 0;
            foreach (var item in itemList)
            {
                GoldShopData gsd = new GoldShopData();
                gsd.ItemName = item.ItemName;
                gsd.BaseId = item.BaseId;
                gsd.ItemPrice = WebDB.getGoldPriceOfItem(item.BaseId);
                gsd.PurchasingNum = itemAndPurchasingNumList.Where(w => w.BaseId.Equals(item.BaseId) && w.ItemName.Equals(item.ItemName)).Select(s => s.Sum).FirstOrDefault().ToString();
                purchasingNumColSum += int.Parse(gsd.PurchasingNum);
                if (string.IsNullOrEmpty(gsd.ItemPrice) == false)
                {
                    gsd.GoldSum = (int.Parse(gsd.ItemPrice) * int.Parse(gsd.PurchasingNum)).ToString();
                }
                GoldSumColSum += int.Parse(gsd.GoldSum);
                gsd.PurchasingPeopleNum = (from tb in itemPurchasingData where tb.BaseId.Equals(item.BaseId) && tb.ItemName.Equals(item.ItemName) select new { tb.CharacterId }).Distinct().Count().ToString();
                PurchasingPeopleNumColSum += int.Parse(gsd.PurchasingPeopleNum);
                //gsd.UsingNum = itemAndUsingNumList.Where(w => w.ItemName.Equals(itemName)).Select(s => s.Sum).FirstOrDefault().ToString() ;
                //gsd.UsingPeopleNum = (from tb in itemConsumingData where tb.ItemName.Equals(itemName) select new { tb.CharacterId }).Distinct().Count().ToString();
                gsdList.Add(gsd);
            }


            //DataTable dt = ConverterWorkData.ToDataTable(gsdList, 3, 0);

            Table table = new Table();
            table.CssClass = "table1";
            table.CellSpacing = 1;
            TableRow rowHeader = new TableRow();
            rowHeader.Cells.AddRange
            (
                new TableCell[]
                {     
                    UIHelpers.CreateTableCell("STT",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                     UIHelpers.CreateTableCell("Id vật phẩm",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                    UIHelpers.CreateTableCell("Tên vật phẩm",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                    UIHelpers.CreateTableCell("Đơn giá vật phẩm",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                    UIHelpers.CreateTableCell("Số lượng mua",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                    UIHelpers.CreateTableCell("Tổng vàng",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                    //UIHelpers.CreateTableCell("Số lượng tiêu hao",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                    UIHelpers.CreateTableCell("Số lượng người đã mua",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                     //UIHelpers.CreateTableCell("Số lượng người đã tiêu hao",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader")       
                }
            );

            table.Rows.Add(rowHeader);
            try
            {
                if (gsdList == null || gsdList.Count == 0)
                {
                    TableRow rowEmpty = new TableRow();
                    rowEmpty.Cells.Add(UIHelpers.CreateTableCell("<p>Không có dữ liệu!</p>", HorizontalAlign.Center, "cell1", 4));
                    table.Rows.Add(rowEmpty);
                }
                else
                {
                    //labelCountOfUser.Text = string.Format("{0:N0}", dt.Rows.Count);
                    string css;
                    int stt = 0;
                    foreach (var dr in gsdList)
                    {
                        stt += 1;
                        css = stt % 2 == 0 ? "cell1" : "cell2";
                        TableRow row = new TableRow();
                        row.Cells.AddRange
                        (
                            new TableCell[]
                           {
                                    UIHelpers.CreateTableCell(stt.ToString(),HorizontalAlign.Center,css),
                                      UIHelpers.CreateTableCell(Converter.ToString(dr.BaseId),HorizontalAlign.Center,css),
                                    UIHelpers.CreateTableCell(Converter.ToString(dr.ItemName),HorizontalAlign.Center,css),
                                    UIHelpers.CreateTableCell(Converter.ToString(dr.ItemPrice),HorizontalAlign.Center,css),
                                    UIHelpers.CreateTableCell(Converter.ToString(dr.PurchasingNum),HorizontalAlign.Center,css),
                                    UIHelpers.CreateTableCell(Converter.ToString(dr.GoldSum),HorizontalAlign.Center,css),
                                    //UIHelpers.CreateTableCell(Converter.ToString(dr.UsingNum),HorizontalAlign.Center,css),
                                    UIHelpers.CreateTableCell(Converter.ToString(dr.PurchasingPeopleNum),HorizontalAlign.Center,css)
                                    //UIHelpers.CreateTableCell(Converter.ToString(dr.UsingPeopleNum),HorizontalAlign.Center,css)
                           }
                        );

                        table.Rows.Add(row);
                    }
                    TableRow lastRow = new TableRow();
                    lastRow.Cells.AddRange
                        (
                            new TableCell[]
                           {
                                    UIHelpers.CreateTableCell(stt.ToString(),HorizontalAlign.Center,""),
                                     UIHelpers.CreateTableCell(Converter.ToString(""),HorizontalAlign.Center,""),
                                    UIHelpers.CreateTableCell(Converter.ToString(""),HorizontalAlign.Center,""),
                                    UIHelpers.CreateTableCell(Converter.ToString(""),HorizontalAlign.Center,""),
                                    UIHelpers.CreateTableCell(Converter.ToString(purchasingNumColSum),HorizontalAlign.Center,""),
                                    UIHelpers.CreateTableCell(Converter.ToString(GoldSumColSum),HorizontalAlign.Center,""),
                                    //UIHelpers.CreateTableCell(Converter.ToString(dr.UsingNum),HorizontalAlign.Center,css),
                                    UIHelpers.CreateTableCell(Converter.ToString(PurchasingPeopleNumColSum),HorizontalAlign.Center,"")
                                    //UIHelpers.CreateTableCell(Converter.ToString(dr.UsingPeopleNum),HorizontalAlign.Center,css)
                           }
                        );
                    table.Rows.Add(lastRow);
                }
            }
            catch (Exception ex)
            {
            }
            return table;
        }
    }
}